package com.hsie.speaker3;


import android.os.Bundle;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class MainActivity extends AppCompatActivity {
    private TextToSpeech tts;
    private ConnectionFactory factory;
    private Connection connection;    //连接
    private Channel channel;//通道
    private boolean IsContinue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tts = new TextToSpeech(this, new listener());
        final MainActivity _this = this;
        new Thread() {
            @Override
            public void run() {
                _this.setupConnectionFactory();
            }
        }.start();
    }

    public void play(View view) {
        CharSequence str = ((EditText) this.findViewById(R.id.editText)).getText();
        tts.speak(str, TextToSpeech.QUEUE_ADD, null, UUID.randomUUID().toString());
    }

    public void comsumer(View view) {
        try {
            Button btn = (Button) view;
            String edit = (String) btn.getText();
            final MainActivity _this = this;
            if ("开始订阅".equals(edit)) {

                btn.setText("取消订阅");
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            _this.channel = _this.connection.createChannel();
                            _this.basicConsume();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            } else {
                this.channel.close();
                btn.setText("开始订阅");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "订阅出错", Toast.LENGTH_LONG).show();
        }
    }

    public void appedText(String msg) {
        EditText txt = this.findViewById(R.id.tConsole);
        CharSequence console = txt.getText();
        txt.setText(console + "\r\n" + msg);
    }

    /**
     * 连接设置
     */
    private void setupConnectionFactory() {
        factory = new ConnectionFactory();
        factory.setHost("192.168.88.101");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        try {
            connection = factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 收消息（从发布者那边订阅消息）
     */
    private void basicConsume() {
        final MainActivity _this = this;
        try {
            //实现Consumer的最简单方法是将便捷类DefaultConsumer子类化。可以在basicConsume 调用上传递此子类的对象以设置订阅：
            channel.basicConsume("rabbitmq_query", false, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);
                    final String msg = new String(body);
                    long deliveryTag = envelope.getDeliveryTag();
                    channel.basicAck(deliveryTag, false);
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MainActivity.this.appedText(msg);
                            MainActivity.this.tts.speak(msg, TextToSpeech.QUEUE_ADD, null, UUID.randomUUID().toString());
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class listener implements TextToSpeech.OnInitListener {

        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                //设置播放语言
                int result = tts.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(MainActivity.this, "不支持", Toast.LENGTH_SHORT).show();
                } else if (result == TextToSpeech.LANG_AVAILABLE) {
                    //初始化成功之后才可以播放文字
                    //否则会提示“speak failed: not bound to tts engine
                    CharSequence str = "初始化成功";
                    tts.speak(str, TextToSpeech.QUEUE_ADD, null, UUID.randomUUID().toString());
                }

            } else {
                Log.e("TAG", "初始化失败");
            }
        }

        public void stopTTS() {
            if (tts != null) {
                tts.shutdown();
                tts.stop();
                tts = null;
            }
        }
    }
}
